import bcrypt
from pyramid.security import remember, forget
from pyramid.view import view_config, forbidden_view_config
from pyramid.httpexceptions import HTTPFound

from .models import Student, Ftprecode, DBSession
from .security import check_password


# 检查加密密码是否一致
def check_password(pw, hashed_pw):
    expected_hash = hashed_pw.encode('utf-8')
    return bcrypt.checkpw(pw.encode('utf-8'), expected_hash)


class MyproView:
    def __init__(self, request):
        self.request = request  # 存储传入的请求对象
        self.logged_in = request.authenticated_userid  # 标记用户是否已登录，存储认证的用户ID

    @view_config(route_name='err500', renderer='./templates/error/500.html')
    def err500(self):
        return {}

    @view_config(route_name='err400', renderer='./templates/error/400.html')
    def err400(self):
        return {}

    @view_config(route_name='index', renderer='./templates/index.html', permission='view')
    def index(self):
        return dict(msg="Hello World")

    @view_config(route_name='login', renderer='./templates/login.html', permission='view')
    @forbidden_view_config(renderer='./templates/login.html')
    def login(self):
        request = self.request  # 获取当前请求对象
        login_url = request.route_url('login')  # 获取登录页面的URL
        referrer = request.url  # 获取请求的来源URL
        if referrer == login_url:
            referrer = '/'  # 如果来源URL是登录页面本身，则将其改为根URL，避免循环登录
        came_from = request.params.get('came_from', referrer)  # 获取表单提交前的位置或默认为来源URL

        message = ''  # 初始化登录消息
        account = ''  # 初始化登录名
        pwd = ''  # 初始化密码
        print('\n\n\n')
        print(self.request.params)
        print('\n\n\n')
        if 'form.submitted' in request.params:  # 检查表单是否已提交
            # print('\n\n\n')
            # print(request.params)
            account = request.params['loginUser']  # 从请求中获取登录名
            pwd = (request.params['loginPassword'])  # 从请求中获取密码
            one = DBSession.query(Ftprecode).filter(Ftprecode.account == account).first()
            # print(one.pwd)

            # if hashed_pw and check_password(password, hashed_pw):
            if one and check_password(pwd, one.pwd):
                headers = remember(request, account)  # 设置记住登录的头部信息
                return HTTPFound(location="/first",
                                 headers=headers)  # 重定向回登录前的页面
            message = 'Failed login'  # 登录失败消息

        # 返回登录页面需要展示的数据
        return dict(
            name='Login',
            message=message,
            url=request.application_url + '/login',
            came_from=came_from,
            account=account,
            pwd=pwd,
        )

    @view_config(route_name='logout')
    def logout(self):
        request = self.request  # 获取当前请求对象
        headers = forget(request)  # 调用forget函数，生成用于忘记会话的头信息
        url = request.route_url('login')  # 根据路由名 'login' 生成回家页的URL
        # 返回一个重定向响应，前往home页面，并携带headers中的头信息
        return HTTPFound(location=url,
                         headers=headers)

    @view_config(route_name='user_verify', renderer='json', request_method="GET")
    def user_verify(self):  # 验证账号是否存在
        account = self.request.params['loginUser']
        one = DBSession.query(Ftprecode).filter(Ftprecode.account == account).first()
        if one:  # 表示存在账户
            data = {'msg': '', 'code': '200'}
            return data
        else:
            data = {'msg': '账户不存在', 'code': '220'}
            return data

    @view_config(route_name='first', renderer='./templates/first.html', permission='read')
    def first(self):
        print(self.request.authenticated_userid)
        students = DBSession.query(Student).all()
        stu_list = []
        for i in students:
            stu = {"id": i.id, "name": i.name, "percent": i.percent}
            stu_list.append(stu)
        return dict(stu_list=stu_list)

    @view_config(route_name='second', renderer='./templates/second.html', permission='view')
    def second(self):
        return {}
